package test.demos.redislock.pojo;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import test.demos.utils.DuRedisUtils;

/**
 * 模拟分布式环境中的ID生成
 * 
 * @author lixiaohui
 * 
 */
public class IDGeneratorByRedisson{

    private RedissonClient  lock;

    private DuRedisUtils redisUtils;

    public IDGeneratorByRedisson(RedissonClient lock,DuRedisUtils redisUtils) {
        this.lock = lock;
        this.redisUtils = redisUtils;
    }

    public String getAndIncrement() {
        RLock rlook = lock.getLock("key");
        rlook.lock(20,TimeUnit.SECONDS);
        String returnVal =  getAndIncrement0();
        rlook.unlock();
        return returnVal;
    }

    private String getAndIncrement0() {
        String number = (String)redisUtils.get("number");
        int numberInt = 0;
        if(StringUtils.isEmpty(number)){
            numberInt = 1;
        }else{
            numberInt = Integer.parseInt(number);
            numberInt ++;
        }
        redisUtils.set("number", String.valueOf(numberInt));
        return String.valueOf(numberInt);
    }
    
//    private String getAndIncrement1() {
//        String number = String.valueOf(redisUtils.incr("1"));
//        return number;
//    }
}